<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'

const props = withDefaults(
  defineProps<{
    src: string
    alt?: string
    class?: string
    lazy?: boolean
    placeholder?: string
  }>(),
  {
    lazy: true, // 添加默认值配置
  }
)

const container = ref<HTMLElement | null>(null)
const isVisible = ref(!props.lazy) // 非懒加载时直接可见
const isLoaded = ref(false)
const hasError = ref(false)

const imgSrc = ref('')

const handleLoad = () => {
  isLoaded.value = true
  hasError.value = false
}
const handleError = () => {
  hasError.value = true
  isLoaded.value = false
}

if (props.lazy !== false) {
  useIntersectionObserver(
    container,
    ([{ isIntersecting }]) => {
      if (isIntersecting) isVisible.value = true
    },
    { threshold: 0.1 }
  )
}

watch(
  () => props.src,
  () => {
    isLoaded.value = false
    hasError.value = false
    if (isVisible.value) imgSrc.value = props.src
  },
  { immediate: true }
)

watch(isVisible, val => {
  if (val) imgSrc.value = props.src
})

onMounted(() => {
  if (!props.lazy) {
    isVisible.value = true
    imgSrc.value = props.src
  }
})
</script>

<template>
  <div ref="container" class="relative h-full w-full" :class="props.class">
    <img
      v-if="isVisible && !hasError"
      :src="imgSrc"
      @load="handleLoad"
      @error="handleError"
      class="h-full w-full rounded-lg object-cover"
      :alt="props.alt"
      v-show="isLoaded"
    />
    <!-- 加载中/错误状态 -->
    <div v-if="!isLoaded || hasError" class="h-full w-full">
      <img
        src="@/assets/png/img_页面空状态_null.png"
        class="h-full w-full scale-75 object-contain"
      />
    </div>
  </div>
</template>
